//
//  FPOnMarkViewController.m
//  BSLCar
//
//  Created by dlios on 15/5/23.
//  Copyright (c) 2015年 lyz. All rights reserved.
//

#import "FPOnMarkViewController.h"
#import "FPOnMarkModel.h"
#import "FirstPageSecondTableViewCell.h"
#import "MJRefresh.h"
#import <UIImageView+WebCache.h>
#import <SDImageCache.h>
#import <AFNetworking.h>

@interface FPOnMarkViewController () <UITableViewDelegate, UITableViewDataSource>

{
    NSInteger pgindex;
    UITableView *table;
//    CGFloat lastContentoffset;
//    BOOL direction;
}

@property (nonatomic, retain) UIActivityIndicatorView *activityIndicator;
@property (nonatomic, retain) NSMutableArray *dataArray;
@property (nonatomic, retain) UIButton *button;

@end

@implementation FPOnMarkViewController

- (void)getParserResult:(NSString *)pageIndex {
    NSString *string = @"http://baojia.qichecdn.com/priceapi3.9.2/services/newcars/get?pageindex=";
    string = [NSString stringWithFormat:@"%@%@&pagesize=20", string, pageIndex];
    string = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:string];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (!connectionError) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *dic2 = [dic objectForKey:@"result"];
            NSArray *array = [dic2 objectForKey:@"serieslist"];
            for (NSDictionary *dic3 in array) {
                FPOnMarkModel *model = [FPOnMarkModel getFPOnMarkModel];
                model.carId = [[dic3 objectForKey:@"id"] stringValue];
                model.imgurl = [dic3 objectForKey:@"imgurl"];
                model.carName = [dic3 objectForKey:@"name"];
                model.newsurl = [dic3 objectForKey:@"newsurl"];
                model.price = [dic3 objectForKey:@"price"];
                model.saletime = [dic3 objectForKey:@"saletime"];
                model.newsTit = [dic3 objectForKey:@"newstitle"];
                [self.dataArray addObject:model];
            }
            [self.activityIndicator stopAnimating];
            //        [self createTableView];
            [table reloadData];
        }
    }];
//    return rootArray;
}

- (void)reachability:(NSString *)pageIndex {
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // -1
                //                NSLog(@"未知");
                [self.activityIndicator stopAnimating];
                break;
            case AFNetworkReachabilityStatusNotReachable: // 0
                //                NSLog(@"无连接");
                [self.activityIndicator stopAnimating];
                [self createTableView];
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi: // 2
                //                NSLog(@"wifi");
              [self getParserResult:pageIndex];
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:  // 1
                //                NSLog(@"3G");
//                [self.activityIndicator stopAnimating];
                [self getParserResult:pageIndex];
                break;
        }
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    pgindex = 1;
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] init];
    item.title = @"返回";
    self.navigationItem.backBarButtonItem = item;
    [item release];

    self.navigationItem.title = @"新车上市";

    self.dataArray = [NSMutableArray array];

    [self createTableView];
    
    self.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
//    self.activityIndicator.backgroundColor = [UIColor grayColor];
    self.activityIndicator.color = [UIColor grayColor];
    self.activityIndicator.center = self.view.center;
    [self.view addSubview:self.activityIndicator];
    [self.activityIndicator startAnimating];
    [_activityIndicator release];
    
    self.button = [UIButton buttonWithType:UIButtonTypeCustom];
//    self.button.backgroundColor = [UIColor redColor];
    [self.button setImage:[UIImage imageNamed:@"iconfont-sh"] forState:UIControlStateNormal];
    self.button.frame = CGRectMake(self.view.bounds.size.width - 40, self.view.bounds.size.height - 110, 30, 30);
//    [self.button setTitle:@"回到顶上" forState:UIControlStateNormal];
    [self.button addTarget:self action:@selector(topButton:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:self.button];
    self.button.hidden = YES;
}

- (void)topButton:(UIButton *)sender {
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
    [table scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

- (void)createTableView {
    table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 64) style:UITableViewStylePlain];
    table.delegate = self;
    table.dataSource = self;
    table.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:table];
   
    [table addHeaderWithTarget:self action:@selector(xiala)];
    [table headerBeginRefreshing];
    
    [table addFooterWithTarget:self action:@selector(shangla)];
    [table footerBeginRefreshing];
    
    [table release];
}

- (void)xiala {
    [table headerEndRefreshing];
}

- (void)shangla {
    pgindex++;
    if (pgindex <= 7) {
        [self reachability:[NSString stringWithFormat:@"%ld", pgindex]];
    } else {
        pgindex = 7;
        UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"没有更多数据了" message:nil delegate:self cancelButtonTitle:@"取消"otherButtonTitles:nil];
        [self.view addSubview:view];
        [view release];
        [view show];
    }
    [table footerEndRefreshing];
}
#pragma mark tableview的代理方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifer = @"cell";
    FirstPageSecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifer];
    if (!cell) {
        cell = [[FirstPageSecondTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
    }
    
 //   cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (indexPath.row == 20) {
        self.button.hidden = NO;
    }
    
    if (indexPath.row == 2) {
        self.button.hidden = YES;
    }
    
    FPOnMarkModel *model = [self.dataArray objectAtIndex:indexPath.row];
    NSURL *url = [NSURL URLWithString:model.imgurl];
    [cell.img sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"Bei"]];
    cell.carNameLabel.text = model.carName;
    cell.priceLabel.text = [NSString stringWithFormat:@"%@万", model.price];
    cell.saletimeLabel.text = [NSString stringWithFormat:@"上市时间: %@", model.saletime];
    
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    OnMarkDetailViewController *scn = [[OnMarkDetailViewController alloc] init];
#pragma -mark 属性传值的中间过程
    FPOnMarkModel *model = [self.dataArray objectAtIndex:indexPath.row];
    scn.idDetail = model.carId;
    scn.carName = model.carName;
    [self.navigationController pushViewController:scn animated:YES];
    
    [scn release];
}

//- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
//    lastContentoffset = scrollView.contentOffset.y;
//}
//
//- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
//    direction = lastContentoffset < scrollView.contentOffset.y;
//    if (direction) {
//        [self.navigationController setNavigationBarHidden:YES animated:YES];
//    }
//}

//- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
//    [self.navigationController setNavigationBarHidden:NO animated:YES];
//}

//- (void)viewWillDisappear:(BOOL)animated {
//     [self.navigationController setNavigationBarHidden:NO animated:YES];
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
